/**
 * Created by Administrator on 2017/3/21.
 */
import React, { Component } from 'react';
import { Form, Input, DatePicker, Select, InputNumber, Button, Tooltip, Icon, Alert } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import request from '@/utils/request';
import find from 'lodash/find';

const FormItem = Form.Item;
const Option = Select.Option;
let uuid = 10;

class AddPoliciesForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      meterArr: [1, 2, 3, 4, 5, 6, 7, 8,9,10],
      meterActiveKey: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
      meter1: [],
      meter2: [],
      meter3: [],
      meter4: [],
      meter5: [],
      meter6: [],
      meter7: [],
      meter8: [],
      meter9: [],
      meter10: [],
    };
  }

  clearTable = () => {
    uuid = 10;
    this.setState({
      meterArr: [1, 2, 3, 4, 5, 6, 7, 8,9,10],
      meterActiveKey: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
      meter1: [],
      meter2: [],
      meter3: [],
      meter4: [],
      meter5: [],
      meter6: [],
      meter7: [],
      meter8: [],
      meter9: [],
      meter10: [],
    });
    this.props.form.resetFields();
  };

  componentDidMount() {
    const that = this;
    // this.fetchMeter('meter1');
    // this.fetchMeter('meter2');
    // this.fetchMeter('meter3');
  }

  fetchMeter = (meter, number) => {
    const that = this;
    request(`/meters`, {
      method: 'GET',
      params: {
        number: number,
        communication_type:1,
        // vendor_id: '124590517324752831',
        // vendor_id: '192297713621090304',
        order_direction: 'desc',
      },
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          [meter]: response.data.data,
        });
      }
    });
  };
  addMeter = () => {
    uuid++;
    this.state.meterArr.push(uuid);
    this.state.meterActiveKey.push(uuid.toString());
    this.setState({
      [`meter${uuid}`]: [],
      meterArr: this.state.meterArr,
      meterActiveKey: this.state.meterActiveKey,
    });
  };
  deleteMeter = (item) => {
    console.log('删除的item', item);
    if (this.state.meterArr.length === 1) {
      console.log('只有一个水表');
      // message.error('至少需要一个水表')
      // return false
    }
    const index = this.state.meterArr.indexOf(item);
    console.log('index', index);
    this.state.meterArr.splice(index, 1);
    this.setState({
      meterArr: this.state.meterArr,
    });
  };
  handleChange = (value, item) => {
    console.log(value);
    console.log(this.state[`meter${item}`]);
    // const address = find(this.state[`meter${item}`], o => o.number === value).address;
    const that = this;
    request(`/meters/${value}`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.props.form.setFieldsValue({
          [`meter_address-${item}`]: response.data.data.address,
          [`pre_meter_date-${item}`]: response.data.data.meter_data.upload_time.substr(0,10),
          [`pre_meter_value-${item}`]: response.data.data.meter_data.value,
        });
      }
    });


  };

  render() {
    const formItemLayoutWithLabel = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 9 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 },
      },
    };

    const { getFieldDecorator } = this.props.form;
    const meterForms = this.state.meterArr.map((item, index) => {
      return (
        <Form style={{ display: 'flex' }} className={'custom-table-form'} key={index} layout="inline">
          <div style={{ width: '50px', lineHeight: '29px', textAlign: 'center', border: '1px solid #d9d9d9' }}>
            {index + 1}
          </div>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}
          >
            {getFieldDecorator(`meter_number-${item}`, {
              initialValue: '',
            })(
              <Select
                style={{ width: '160px' }}
                showSearch
                filterOption={false}
                onSearch={(value) => {
                  this.fetchMeter(`meter${item}`, value);
                }}
                onChange={(value) => this.handleChange(value, `${item}`)}
                notFoundContent={null}
              >
                {this.state[`meter${item}`].map((item, index2) => {
                  return <Option key={index2} value={item.number}>{item.number}</Option>;
                })}
              </Select>,
            )}
          </FormItem>
          <Tooltip title={this.props.form.getFieldValue(`meter_address-${item}`)}>
            <FormItem
              style={{ flex: '1', marginRight: '0' }}
            >
              {getFieldDecorator(`meter_address-${item}`, {
                initialValue: '',
              })(
                <Input style={{ width: '160px' }} disabled={true}/>,
              )}
            </FormItem>
          </Tooltip>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}

          >
            {getFieldDecorator(`meter_value-${item}`, {
              initialValue: '',
            })(
              <Input style={{ width: '160px', fontWeight: 'bold' }}/>,
            )}
          </FormItem>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}

          >
            {getFieldDecorator(`meter_date-${item}`, {
              initialValue: moment(),
            })(
              <DatePicker disabledDate={(currentDate) => currentDate && currentDate > moment().endOf('day')}
                          allowClear={false} style={{ width: '160px' }}/>,
            )}
          </FormItem>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}

          >
            {getFieldDecorator(`pre_meter_value-${item}`, {
              initialValue: '',
            })(
              <Input style={{ width: '160px', fontWeight: 'bold' }} disabled={true}/>,
            )}
          </FormItem>
          <FormItem
            style={{ flex: '1', marginRight: '0' }}

          >
            {getFieldDecorator(`pre_meter_date-${item}`, {
              initialValue: '',
            })(
              <Input style={{ width: '160px' }} disabled={true}/>,
            )}
          </FormItem>

          <div style={{ width: '80px', lineHeight: '29px', textAlign: 'center', border: '1px solid #d9d9d9' }}>
            <Button
              style={{ height: '22px' }}
              type="danger"
              size="small"
              icon="delete"
              onClick={(e) => {
                e.stopPropagation();
                this.deleteMeter(item);
              }
              }
            >删除
            </Button>
          </div>


        </Form>
      );
    });
    return (
      <div>
        <Alert
          message="请注意"
          description="该处为手工录入水表读数，水表地址、上次抄表读值与上次抄表日期自动填充"
          type="info"
          showIcon

        />
        <div style={{ border: '1px solid #d9d9d9', marginTop: '10px' }}>

          <div style={{
            display: 'flex',
            fontWeight: 'bold',
            lineHeight: '32px',
            height: '32px',
            background: 'rgb(249,249,249)',
          }}>
            <div style={{ width: '50px', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>序号</div>
            <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>水表号</div>
            <div style={{
              flex: '1',
              paddingLeft: '10px',
              border: '1px solid #d9d9d9',
              textOverflow: 'ellipsis',
              overflow: 'hidden',
              whiteSpace: 'nowrap',
            }}>水表地址
            </div>
            <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>本次抄表读值(m³)</div>
            <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>本次抄表日期</div>
            <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>上次抄表读值(m³)</div>
            <div style={{ flex: '1', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>上次抄表日期</div>
            <div style={{ width: '80px', paddingLeft: '10px', border: '1px solid #d9d9d9' }}>操作</div>
          </div>
          {meterForms}
          <Button type={'primary'} className={'btn-cyan'} icon={'plus'} block onClick={this.addMeter}>添加行</Button>

        </div>
        <Button type={'danger'} style={{ marginTop: '12px' }} icon={'table'} onClick={this.clearTable}>初始化表格</Button>
      </div>

    );
  }
}

const AddPoliciesFormWrap = Form.create()(AddPoliciesForm);
export default connect()(AddPoliciesFormWrap);


